﻿using System;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Threading;
using MusicFluent.Models;
using MusicFluent.MusicViews;
using MusicFluent.ViewModels.Pages;
using MusicFluent.Views;
using NetEasyMusic.Lib.Models;
using NetEasyMusic.Lib.Recommend;

namespace MusicFluent.Pages;

public partial class VideoView : UserControl
{
    private BannerModel[] _banners = [];

    public VideoView()
    {
        InitializeComponent();
    }

    protected override async void OnInitialized()
    {
        var main = ViewOpera.GetView<MainWindow>(this);
        if (main == null) return;
        main.TaskShow();
        if (DataContext is not VideoViewModel model) return;
        _banners = await model.Video.Banner();
        var recommendItems = await model.Video.VideoTask();
        main.TaskShow();
        VideoItems.ItemsSource = recommendItems.Items;
        Block.Text = recommendItems.Name;
        Carousel.ItemsSource = _banners;
        StartAutoSwitchTimer();
    }

    private void StartAutoSwitchTimer()
    {
        var dispatcherTimer =
            new DispatcherTimer(TimeSpan.FromSeconds(5), DispatcherPriority.Normal, AutoSwitchTimerCallback);
        dispatcherTimer.Start();
    }

    private async void AutoSwitchTimerCallback(object? sender, EventArgs e)
    {
        var result = await Dispatcher.UIThread.InvokeAsync(() => Carousel.SelectedIndex);
        Dispatcher.UIThread.Post(() => Carousel.SelectedIndex = (result + 1) % _banners.Length);
    }

    private void VideoTapped(object? sender, TappedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not VideoModel model) return;
        var main = ViewOpera.GetView<MainWindow>(this);
        if (main == null) return;
        main.TaskShow();
        var view = new VlcView(model);
        main.Navigate(view);
        main.TaskShow();
    }
}